//
//  XMPPTool.m
//  E_ChatRoom
//
//  Created by rimi1 on 15/6/27.
//  Copyright (c) 2015年 TJ. All rights reserved.
//

#import "XMPPTool.h"
#import "LogInViewController.h"
/**
 * 1.初始化XMPPStream
 * 2.链接到服务器(传一个JID)
 * 3.连接到服务器成功后,再发送密码授权
 * 4.授权成功后,发送“在线”消息
 */
@interface XMPPTool ()<XMPPStreamDelegate>{
    
    XMPPResultBlock _resultBlock;
//    XMPPRoom *_chatRoom;
    XMPPRoomCoreDataStorage *_roomStorage;
}

//1.初始化XMPPStream
- (void)setupXMPPStream;

//2.链接到服务器(传一个JID)
- (void)connectToHost;

//3.连接到服务器成功后,再发送密码授权
- (void)sendPwdToHost;

//4.授权成功后,发送“在线”消息
- (void)sendOnlineToHost;
@end

@implementation XMPPTool

singleton_implementation(XMPPTool)



#pragma mark - 私有方法
/**
 *  初始化XMPPStream
 */
- (void)setupXMPPStream{
    
    _xmppStream = [[XMPPStream alloc] init];
    
    // 添加聊天室模块
    _roomStorage = [[XMPPRoomCoreDataStorage alloc] init];
    
//    XMPPJID *roomJid = [XMPPJID jidWithString:[NSString stringWithFormat:@"%@@%@",@"123",RoomService]];
//    _chatRoom = [[XMPPRoom alloc] initWithRoomStorage:_roomStorage jid:roomJid dispatchQueue:dispatch_get_main_queue()];
//
//    // 激活聊天室模块
//    [_chatRoom activate:_xmppStream];
    
    //设置代理
    [_xmppStream addDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
}

- (void)creatChatRoom:(XMPPJID *)roomJid {
    _chatRoom = [[XMPPRoom alloc] initWithRoomStorage:_roomStorage jid:roomJid dispatchQueue:dispatch_get_main_queue()];
    
    // 激活聊天室模块
    [_chatRoom activate:_xmppStream];
}


- (void)teardownXmpp {
    // 移除代理
    [_xmppStream removeDelegate:self];
    
    // 停止模块
    [_chatRoom deactivate];
    
    // 断开连接
    [_xmppStream disconnect];
    
    // 清空资源
    _chatRoom = nil;
    _roomStorage = nil;
    _xmppStream = nil;
}

/**
 *  链接到服务器(传一个JID)
 */
- (void)connectToHost{
    
    //1.初始化_xmppStream
    if (!_xmppStream) {
        
        [self setupXMPPStream];
    }
    
    //2.从单例获取用户
    NSString *user =  nil;
    if (self.isRegisterOperation) {
        user = [UserInfo sharedUserInfo].registerUser;
    } else {
        user = [UserInfo sharedUserInfo].user;
    }
    
    NSLog(@"user:%@",user);
    //3.配置_xmppStream的JID
    XMPPJID *myJID = [XMPPJID jidWithUser:user domain:@"rimimac.local" resource:@"iphone"];
    _xmppStream.myJID = myJID;
    
    //4.配置_xmppStream的HostName(不仅可以是域名，还可是IP地址
    _xmppStream.hostName = MyDomain;
    
    //5.配置端口号
    _xmppStream.hostPort = 5222;
    
    //6.发起链接
    NSError *err = nil;
    if (![_xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&err]) {
        
        TJLog(@"%@",err);
    }
}

/**
 *  连接到服务成功后，再发送密码授权
 */
- (void)sendPwdToHost{
    
    NSError *err = nil;
    //1.从单例里获取密码
    NSString *pwd = [UserInfo sharedUserInfo].pwd;
    
    //2.发送密码授权
    [_xmppStream authenticateWithPassword:pwd error:&err];

    //3.打印错误信息
    if (err) {
        
        TJLog(@"%@",err);
    }
}

/**
 *  发送在线消息
 */
- (void)sendOnlineToHost{
    
    //1.创建presence对象
    XMPPPresence *presence = [XMPPPresence presence];
    
    //2.发送presence对象
    [_xmppStream sendElement:presence];
}




#pragma mark - XMPPStream 代理方法

/*与主机连接成功(登陆或注册)*/
- (void)xmppStreamDidConnect:(XMPPStream *)sender{
    
    if (self.isRegisterOperation) {
        
        //注册操作，发送注册的密码
        NSString *pwd = [UserInfo sharedUserInfo].registerPwd;
        [_xmppStream registerWithPassword:pwd error:nil];
    }else{
        
        // 主机连接成功后，发送密码进行授权
        [self sendPwdToHost];
    }
}

/*与主机断开连接*/
-(void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error{
    
    // 如果有错误，代表连接失败
    // 如果没有错误，表示正常的断开连接(人为断开连接)
    
    if(error && _resultBlock){
        _resultBlock(XMPPResultTypeNetErr);
    }
    TJLog(@"与主机断开连接 %@",error);
}

/*授权成功*/
-(void)xmppStreamDidAuthenticate:(XMPPStream *)sender{
    
    [self sendOnlineToHost];
    
    // 回调控制器登录成功
    if(_resultBlock){
        _resultBlock(XMPPResultTypeLoginSuccess);
    }
}

/*授权失败*/
-(void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(DDXMLElement *)error{
   
    TJLog(@"授权失败 %@",error);
    
    // 判断block有无值，再回调给登录控制器
    if (_resultBlock) {
        _resultBlock(XMPPResultTypeLoginFailure);
    }
}

/*注册成功*/
-(void)xmppStreamDidRegister:(XMPPStream *)sender{
    
    if(_resultBlock){
        _resultBlock(XMPPResultTypeRegisterSuccess);
    }
}

/*注册失败*/
-(void)xmppStream:(XMPPStream *)sender didNotRegister:(DDXMLElement *)error{
    
    TJLog(@"注册失败 %@",error);
    if(_resultBlock){
        _resultBlock(XMPPResultTypeRegisterFailure);
    }
    
}



#pragma mark - 公有方法

/*用户注销*/
- (void)xmppUserlogout{
    
    //1.发送“离线”消息
    XMPPPresence *offline = [XMPPPresence presenceWithType:@"unawailable"];
    [_xmppStream sendElement:offline];
    
    //2.与服务器断开连接
    [_xmppStream disconnect];
    
    //3.回到登陆界面
    [UIApplication sharedApplication].keyWindow.rootViewController = [[LogInViewController alloc] init];
    
    //4.更新用户的登陆状态并保存
    [UserInfo sharedUserInfo].loginStatus = NO;
    [[UserInfo sharedUserInfo] saveUserInfoToSanbox];
}

/*用户登录*/
- (void)xmppUserLogin:(XMPPResultBlock)resultBlock{
    
    //1.保存block
    _resultBlock = resultBlock;
    
    //2.每次登陆前，先断开与服务器的连接
    [_xmppStream disconnect];
    
    //3.链接主机, 成功后发送登陆密码
    [self connectToHost];
}

/*用户注册*/
- (void)xmppUserRegister:(XMPPResultBlock)resultBlock{
    
//    // 1.先把block存起来
//    _resultBlock = resultBlock;
//    
//    // 2.如果以前连接过服务，要断开
//    [_xmppStream disconnect];
//    
//    // 3.连接主机 成功后发送注册密码
//    [self connectToHost];
    [self xmppUserLogin:resultBlock];
}

- (void)dealloc {
    [self teardownXmpp];
}

@end
